class EventController < ApplicationController
  
  before_filter :login_required
  before_filter :instructor_required, :only => [:add_assignment]
  def list_own
    @to_list = self.current_user.events
  end

  # Recibe un ID, y muestra el Evento con id ID a detalle:
  #  NOMBRE del evento
  #  Curso relacionado (nombre)
  #  Fecha de ocurrencia (due_date)
  #  Fecha de finalización (expire_date)
  #  Descripcion (si es un archivo, una liga para bajarlo, si no, la descripción
  #  completa, in-line)
  #
  def view
    @to_view = Event.find(params[:id], :include => :course, :order => "due_date DESC")
    descr = EventBlob.find(:first, :conditions => { :event_id => @to_view.id }, :select => 'id, kind')
    @description_kind = descr.kind 
    if @description_kind != 1
      @description = @to_view.event_blob
    else
      @description = descr.id 
    end
  rescue ActiveRecord::RecordNotFound
    flash[:error] = "Evento desconocido! #{params[:id]}"
    redirect_to :controller => 'account', :action => 'index'
  end

  # Recibe un ID, y descarga la descripcion del archivo
  def get
    @desc = EventBlob.find(params[:id])
    send_data @desc.data, :filename => @desc.file_name 
  rescue ActiveRecord::RecordNotFound
    flash[:error] = "No puedo encontrar la descripcion: #{params[:id]}"
    redirect_to :controller => 'account', :action => 'index'
  end

  # Crea un nuevo evento (relacionado con un curso con id = params[:id]
  def add
    if params[:id].nil?
      flash[:error] = "No pude encontrar el curso sin id."

      redirect_to (:controller => 'account', :action => 'index') 
      return 
    end
    @assignment = false
    @desc = Event.new(params[:desc])
    @desc.course = Course.find(params[:id])

    if not @desc.course.users.include?(self.current_user) and not @desc.course.creator == self.current_user
      self.access_denied 
      return 
    end

    @desc.user = self.current_user
    if not params[:desc_data].nil? and not params[:desc_data][:data].nil? and params[:desc_data][:kind] == 1
      @desc_data = EventBlob.new(:kind => 1, :data => params[:desc_data][:data].read, :file_name => params[:desc_data][:data].original_filename)
    else
      @desc_data = EventBlob.new(params[:desc_data])
    end
    @desc_data.event = @desc
    # Estos si funcionan!
#    logger.warn(@desc_data.to_yaml)
#    logger.warn(params[:desc_data][:data].to_yaml) rescue logger.warn("desc_data.data is nil")
#    logger.warn(params[:desc_data][:data].original_filename) rescue logger.warn("desc_data.data is nil")
#    logger.warn(params[:desc_data][:data].read) rescue logger.warn("desc_data.data is nil")
#    logger.warn(params[:desc_data].is_a?(File))

    return if not request.post?

    @desc_data.event = @desc
    Event.transaction {
      @desc.save!
      @desc_data.save!
    } 
    redirect_to :controller => 'account', :action => 'index'
  rescue ActiveRecord::RecordInvalid
#  rescue Exception => e
#    flash[:error] = e.backtrace().join("\n")
  end

  # Crea una nueva assignacions (relacionado con un curso con id = params[:id]
  def add_assignment
    @assignment = true
    if params[:id].nil?
      flash[:error] = "No pude encontrar el curso sin id."

      redirect_to (:controller => 'account', :action => 'index') 
      return 
    end
    @desc = Assignment.new(params[:desc])
    @desc.course = Course.find(params[:id])

    if not @desc.course.users.include?(self.current_user) and not @desc.course.creator == self.current_user
      self.access_denied 
      return 
    end

    @desc.user = self.current_user
    if not params[:desc_data].nil? and not params[:desc_data][:data].nil? and params[:desc_data][:kind] == 1
      @desc_data = EventBlob.new(:kind => 1, :data => params[:desc_data][:data].read, :file_name => params[:desc_data][:data].original_filename)
    else
      @desc_data = EventBlob.new(params[:desc_data])
    end
    @desc_data.assignment= @desc
    # Estos si funcionan!
#    logger.warn(@desc_data.to_yaml)
#    logger.warn(params[:desc_data][:data].to_yaml) rescue logger.warn("desc_data.data is nil")
#    logger.warn(params[:desc_data][:data].original_filename) rescue logger.warn("desc_data.data is nil")
#    logger.warn(params[:desc_data][:data].read) rescue logger.warn("desc_data.data is nil")
#    logger.warn(params[:desc_data].is_a?(File))
    
    return if not request.post?

    @desc_data.event = @desc
    Assignment.transaction {
      @desc.save!
      @desc_data.save!
    } 
    redirect_to :controller => 'account', :action => 'index'
  rescue ActiveRecord::RecordInvalid
#  rescue Exception => e
#    flash[:error] = e.backtrace().join("\n")
  end
#TODO: TERMINAR!!
  #"Interfaces y ponerle ligas por todos lados para que haga eso"
  def remove
    redirect_to :controller => 'course', :action => 'list'
    return if params[:id].nil?
    return if not (self.is_admin? or self.current_user != Event.find(params[:id]).user)
    Event.destroy(params[:id])
  rescue
    flash[:error] = "ID desconocido: #{params[:id]}"
    redirect_to :controller => 'course', :action => 'list'
  end

  def answer_assignment

  end
end
